package service

import (
	"demo/basic/config"
	"demo/handler/model"
	"demo/handler/request"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

func AddLike(c *gin.Context) {
	var form request.AddLike
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	userId := c.GetFloat64("userId")
	var like model.Like
	if err := like.IsLike(config.DB, int(userId), form.PostId); err != nil {
		like = model.Like{
			UserId: int(userId),
			PostId: form.PostId,
		}
		err = like.AddLike(config.DB)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "点赞失败"})
			return
		}
		config.DB.Model(&model.Post{}).Where("id = ?", form.PostId).
			Update("count", gorm.Expr("count + 1"))
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "点赞成功"})
		return
	}
	config.DB.Delete(&model.Like{}, like.ID)
	config.DB.Model(&model.Post{}).Where("id = ?", form.PostId).
		Update("count", gorm.Expr("count - 1"))
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "取消点赞成功",
	})
	return

}
